﻿using ICSharpCode.SharpZipLib.GZip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace BigFileSearcher
{
    public class CommStreamReader
    {
        private GZipInputStream gzipFile;
        private StreamReader streamReader;
        private Encoding encoding;
        private List<byte> buffer = new List<byte>(2048);
        public CommStreamReader(string fileName, Encoding encoding, bool detectEncodingFromByteOrderMarks)
        {
            this.encoding = encoding;
            if (Path.GetExtension(fileName).ToUpper() == ".GZ")
            {
                gzipFile = new GZipInputStream(File.OpenRead(fileName));
            }
            else
            {
                streamReader = new StreamReader(fileName, encoding, detectEncodingFromByteOrderMarks);
            }
        }

        public string ReadLine()
        {
            if (streamReader != null)
            {
                return streamReader.ReadLine();
            }
            while (true)
            {
                int r = gzipFile.ReadByte();
                if (r == -1)
                {
                    break;
                }
                byte c = (byte)r;
                if (Is_NewLineChar(c))
                {
                    if (buffer.Count > 0)
                    {
                        break;
                    }
                }
                else
                {
                    buffer.Add(c);
                }
            }
            if (buffer.Count > 0)
            {
                string s = encoding.GetString(buffer.ToArray());
                buffer.Clear();
                return s;
            }
            return null;
        }

        private static bool Is_NewLineChar(byte c)
        {
            return c == '\r' || c == '\n';
        }

        internal void Close()
        {
            if (gzipFile != null)
            {
                gzipFile.Close();
            }
        }
    }
}
